<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\model\User as UserModel;

class User extends BaseController
{
    
    public function list($page = 1,$q='')
    {
        //$student = new StudentModel;
        $q = input('get.q');
        $pageParam = ['query' => []];
        //$list = StudentModel::order('stu_id desc')->paginate(15);
        if($q){
            $pageParam['query']['q'] = $q;
            //$q2 = base64_encode($q);
            $list = UserModel::where('nickname','LIKE',"%$q%")->order('subscribe desc')->paginate(15,false,$pageParam);            
        }else{
            $list = UserModel::order('subscribe desc')->paginate(15);
        }
        
        $userCount = UserModel::count();

        $this->assign('userCount',$userCount);
        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('q',$q);
        return $this->fetch();
    }

    public  function update_list()
    {
        $weixin = new \weixin\wxapi();

        $result = $weixin->get_user_list();
        //dump($result);die;
        $openidlist = UserModel::column('openid');
        //dump($openidlist);die;
        $openidlist = (count($openidlist)> 0) ? $openidlist:array();

        $newfollow = array_diff($result["data"]["openid"], $openidlist);
        $cancelfollow = array_diff($openidlist, $result["data"]["openid"]);
        //dump($newfollow);die;
        //dump($cancelfollow);die;
        foreach ($newfollow as &$openid) {
            $data = array();
            $data['openid'] = $openid;
            UserModel::create($data);
        }
        foreach ($cancelfollow as &$openid){
            $data = array();
            $data['openid'] = $openid;
            UserModel::destroy($data);
        }
        $this->success('检测到新增关注用户数：'.count($newfollow).'，取消关注用户数：'.count($cancelfollow),'updateInfo');

    }

    public function updateInfo(){
        $weixin = new \weixin\wxapi();
        
        //$User = M("User");
        //$updateUser = $User->where("`subscribe` =  ''")->limit(rand(90, 100))->select(); 
        $updateUser = UserModel::where('subscribe',NULL)->limit(rand(90,100))->select();
        //dump($updateUser);die;
        
        if (count($updateUser) > 0){
            $municipalities = array("北京", "上海", "天津", "重庆", "香港", "澳门");
            $sexes = array("", "男", "女");

            $new = 0;
            $data = array();
            foreach ($updateUser as &$user) {
                $new ++;
                $info = $weixin->get_user_info($user['openid']);
                 //dump($info);die;
                $data = array();
                if (!isset($info["subscribe"])){
                    // var_dump("1111111111");
                    // $this->error('微信服务器出错!<br>该用户未返回有效数据，可尝试删除该用户后继续更新。<br>OpenID：'.$user['openid'],'index', 60);
                    $data['subscribe'] = 0;
                    //$User->where("`openid` = '".$user['openid']."'")->save($data); // 根据条件更新记录
                    UserModel::where('openid',$user['openid'])->update($data);
                    //UserModel::where('openid',$user['openid'])->delete();
                    //exit;
                }else if ($info['subscribe'] == 0){
                    //var_dump("222222222222");
                    //$User->where("`openid` = '".$user['openid']."'")->delete(); // 未关注删除
                    UserModel::where('openid',$user['openid'])->delete();
                }else{
                    //var_dump("3333333333");
                    //$data['nickname'] = str_replace("'", "", $info['nickname']);
                    //$data['nickname'] = base64_encode($info['nickname']);
					$data['nickname'] = $info['nickname'];
                    $data['sex'] = $sexes[$info['sex']];
                    $data['country'] = $info['country'];
                    $data['province'] = $info['province'];
                    $data['city'] = (in_array($info['province'], $municipalities))?$info['province'] : $info['city'];
                    $data['headimgurl'] = $info['headimgurl'];
                    $data['subscribe'] = $info['subscribe_time'];
                    $data['heartbeat'] = $info['subscribe_time'];
                    $data['remark'] = $info['remark'];
                    $data['tagid'] = json_encode($info['tagid_list']);
                    //$User->where("`openid` = '".$user['openid']."'")->save($data); // 根据条件更新记录
                    UserModel::where('openid',$user['openid'])->update($data);
                }
            }
            
            $this->success(date("H:i:s",time()).' 更新了'.$new.'个用户','updateInfo');
        }else{
            $this->success('更新完成','list');
        }
	}	

    //微信会员
    public function member($page = 1,$q='')
    {
        $q = input('get.q');
        $pageParam = ['query' => []];
        $map1 = array();
        $map1['status'] = ['EGT',0];
        if($q){
            $pageParam['query']['q'] = $q;
            //$q2 = base64_encode($q);
            $map2 = array();
            $map2['status'] = ['EGT',0];
            $map2['nickname'] = ['like',"%$q%"];
            $list = UserModel::where($map2)->order('subscribe desc')->paginate(15,false,$pageParam);            
        }else{
            
            $list = UserModel::where($map1)->order('subscribe desc')->paginate(15);
        }
        
        $userCount = UserModel::where($map1)->count();

        $this->assign('userCount',$userCount);
        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('q',$q);
        return $this->fetch();

    }

    //微信会员状态改变
    public function change($openid, $status)
    {
        
		if (!empty($openid) && !empty($status)) {
            //$User = M("User");
            $data['status'] = $status;
            
            $weixin = new \weixin\wxapi();
            
            
            //大写样式，基础消息接口格式，已兼容
            if ($status == 1){
                $content[] = array("Title"=>"会员身份审核通过", "Description"=>"点击进入领取优惠券", "PicUrl"=>"", "Url" =>"http://wx.lphcy.com/home/user/index");
            }else{
                $data['status'] = $status;
                $data['fullname'] = "";
                $data['mobile'] = "";
                $data['cardno'] = "";
                $data['birthday'] = "";
                $data['address'] = "";
                $content[] = array("Title"=>"会员身份审核不通过", "Description"=>"请勿填写虚拟资料\n如果你确认已有会员卡号，可以点击进入重新填写", "PicUrl"=>"", "Url" =>"http://wx.lphcy.com/home/user/index");
            }
            //$User->where("`openid` = '".$openid."'")->save($data); // 根据条件更新记录
            UserModel::where('openid',$openid)->update($data);

            $result = $result = $weixin->send_custom_message($openid, "news", $content);
            $this->success('操作成功!');
            
        } else {
            $this->error('参数错误！');
        }
    }
}